const express = require('express');
const router = express.Router();
const Pattern = require('../models/Pattern');
const auth = require('../middleware/auth');

/**
 * @route   GET api/patterns
 * @desc    Get all patterns
 * @access  Public
 */
router.get('/', async (req, res) => {
  try {
    const patterns = await Pattern.find().sort({ order: 1 });
    res.json(patterns);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

/**
 * @route   GET api/patterns/:id
 * @desc    Get pattern by ID
 * @access  Public
 */
router.get('/:id', async (req, res) => {
  try {
    const pattern = await Pattern.findById(req.params.id);
    
    if (!pattern) {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    res.json(pattern);
  } catch (err) {
    console.error(err.message);
    
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    res.status(500).send('Server Error');
  }
});

/**
 * @route   GET api/patterns/category/:category
 * @desc    Get patterns by category
 * @access  Public
 */
router.get('/category/:category', async (req, res) => {
  try {
    const patterns = await Pattern.find({ 
      category: req.params.category 
    }).sort({ order: 1 });
    
    res.json(patterns);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

/**
 * @route   POST api/patterns
 * @desc    Create a pattern
 * @access  Private/Admin
 */
router.post('/', auth, async (req, res) => {
  // Check if user is admin
  if (req.user.role !== 'admin') {
    return res.status(403).json({ msg: 'Not authorized' });
  }
  
  const {
    name,
    category,
    description,
    intent,
    applicability,
    structure,
    participants,
    collaborations,
    consequences,
    implementation,
    sampleCode,
    knownUses,
    relatedPatterns,
    order
  } = req.body;
  
  try {
    // Check if pattern already exists
    let pattern = await Pattern.findOne({ name });
    
    if (pattern) {
      return res.status(400).json({ msg: 'Pattern already exists' });
    }
    
    // Create new pattern
    pattern = new Pattern({
      name,
      category,
      description,
      intent,
      applicability,
      structure,
      participants,
      collaborations,
      consequences,
      implementation,
      sampleCode,
      knownUses,
      relatedPatterns,
      order
    });
    
    await pattern.save();
    res.json(pattern);
  } catch (err) {
    console.error(err.message);
    res.status(500).send('Server Error');
  }
});

/**
 * @route   PUT api/patterns/:id
 * @desc    Update a pattern
 * @access  Private/Admin
 */
router.put('/:id', auth, async (req, res) => {
  // Check if user is admin
  if (req.user.role !== 'admin') {
    return res.status(403).json({ msg: 'Not authorized' });
  }
  
  try {
    const pattern = await Pattern.findById(req.params.id);
    
    if (!pattern) {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    // Update fields
    const updateFields = { ...req.body };
    Object.keys(updateFields).forEach(key => {
      pattern[key] = updateFields[key];
    });
    
    await pattern.save();
    res.json(pattern);
  } catch (err) {
    console.error(err.message);
    
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    res.status(500).send('Server Error');
  }
});

/**
 * @route   DELETE api/patterns/:id
 * @desc    Delete a pattern
 * @access  Private/Admin
 */
router.delete('/:id', auth, async (req, res) => {
  // Check if user is admin
  if (req.user.role !== 'admin') {
    return res.status(403).json({ msg: 'Not authorized' });
  }
  
  try {
    const pattern = await Pattern.findById(req.params.id);
    
    if (!pattern) {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    await pattern.remove();
    res.json({ msg: 'Pattern removed' });
  } catch (err) {
    console.error(err.message);
    
    if (err.kind === 'ObjectId') {
      return res.status(404).json({ msg: 'Pattern not found' });
    }
    
    res.status(500).send('Server Error');
  }
});

module.exports = router; 